package com.farsunset.ichat.cim.handler;

import java.util.List;

import org.apache.log4j.Logger;

import com.farsunset.cim.nio.constant.CIMConstant;
import com.farsunset.cim.nio.handler.CIMRequestHandler;
import com.farsunset.cim.nio.mutual.Message;
import com.farsunset.cim.nio.mutual.ReplyBody;
import com.farsunset.cim.nio.mutual.SentBody;
import com.farsunset.cim.nio.session.CIMSession;
import com.farsunset.ichat.cim.session.MessageManager;
import com.farsunset.ichat.common.util.ContextHolder;
import com.kuaigou.cim.util.AESEncodeUtil;
/**
 * 推送离线消息
 */
public class PushOfflineMessageHandler implements CIMRequestHandler {
	protected final Logger logger = Logger.getLogger(PushOfflineMessageHandler.class);

	public ReplyBody process(CIMSession ios, SentBody message) {
		MessageManager messageManager= ((MessageManager) ContextHolder.getBean("messageManager"));
		
		ReplyBody reply = new ReplyBody();
		reply.setCode(CIMConstant.ReturnCode.CODE_200);
		
		String account = message.get("account");
		String verificationCode = message.get("verificationCode");		
		try {
			if(verificationCode == null ||  !account.equals(AESEncodeUtil.decrypt(verificationCode,AESEncodeUtil.key))){
				reply.setCode(CIMConstant.ReturnCode.CODE_403);
				return reply;
			}
		} catch (Exception e1) {
			reply.setCode(CIMConstant.ReturnCode.CODE_500);
			return reply;
		}			
		
		// android才有离线消息
		if(CIMConstant.MobileChannel.CHANNEL_ANDROID == Short.parseShort((String)message.get("channel"))){	
			account = message.get("account");
			try {				
				//获取到存储的离线消息
				List<Message> list = messageManager.getOfflineMessage(account);				
				for (Message m : list) {
					if(CIMConstant.MobileChannel.CHANNEL_ANDROID == m.getChannel()){
						ios.write(m);
					}
				} 				
			} catch (Exception e) {
				reply.setCode(CIMConstant.ReturnCode.CODE_500);
				logger.error("拉取离线消息失败", e);
			}finally{
				messageManager.removeMessage(account);
			}
		}
		return reply;
	}
}